<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\AppException;
use App\Models\Answer;
use App\Models\Config;
use App\Models\Data;
use App\Models\Member;
use App\Models\MemberAnswer;
use App\Models\OrganizationSubject;
use App\Models\OrganizationSubjectNum;
use App\Models\Problem;
use App\Models\ScoreRecord;
use App\Models\Subject;
use App\Services\ExcelExportService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProblemController extends BaseController
{
    /**
     * 首页数据
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $params = $request->all();
        //pc端展示
        $build = Problem::query();
        if (isset($params['last_question_id']) && !empty($params['last_question_id'])){
            $build->where('pid', '>=', $params['last_question_id']);
        }
        $pageSize = $request->input('pageSize', 50);
        $data = $build->paginate($pageSize);
        foreach ($data as $key => $value){
            $data[$key]['answer'] = Answer::query()->where('pid', $value['pid'])->get()->toArray();
        }

        return $this->success($data);
    }

    /**
     * 答题人获取题目api
     * @param $id
     * @param Request $request
     * @return array
     */
    public function memberProblemIndex($id, Request $request)
    {

        $params = $request->all();//判断每日最多可以答题的次数



        $tiku = OrganizationSubject::query()->where('organization_id', $id)->first()->toArray();

        $data = Problem::query()->whereIn('sid', explode(',', $tiku['subject_id']))->get()->toArray();
        $config = Config::query()->first()->toArray();
        if (empty($data)){
            $config['status'] = 0;
            $result['question'] = $data;
            $result['question_num'] = count($data);
            $result['subject_name'] = '';
            $result['config'] = $config;
            return $this->success($result);
        }

        $allNum = count($data);

        $subjectNum = OrganizationSubjectNum::query()->where('organization_id', $id)->pluck('num')->toArray();

        $all = array_column($data, 'pid', null);

        $subNum =  array_sum($subjectNum) > $allNum ? $allNum  :  array_sum($subjectNum);

        $subNumIds =  array_rand($all, $subNum);

        $ids = [];

        foreach ($all as $key => $value){
            if (in_array($key, $subNumIds)){
                $ids[] = $value;
            }
        }

        if (isset($params['type']) && $params['type']  == 2){
            $ids = explode(',', $params['pid_ids']);
            $data = Problem::query()->whereIn('pid', $ids)->get()->toArray();
        }else{
            $data = Problem::query()->whereIn('pid', $ids)->get()->toArray();
        }

        $subject = Subject::query()->whereIn('sid', explode(',', $tiku['subject_id']))->pluck('name')->toArray();

        foreach ($data as $key => $value){
            $data[$key]['answer'] = Answer::query()->where('pid', $value['pid'])->get()->toArray();
        }
        $config = Config::query()->first()->toArray();

        $result['question'] = $data;
        $result['question_num'] = count($data);
        $result['subject_name'] = implode(',', $subject);
        $result['config'] = $config;
        return $this->success($result);
    }


    /**
     * @param $id  //完成答题人ID
     * @param Request $request
     * @return array
     */
    public function memberAnswer($id, Request $request)
    {
        $params = $request->all();//判断每日最多可以答题的次数


        if (!isset($params['num'])){
            return $this->errorCode(10001, [], '对不起，轮次参数未上传');
        }

        $member = Member::query()->where('member_id', $id)->first()->toArray();
        if ($member['status'] == 1){
            return $this->errorCode(200, [], '对不起，您已经答题过了');
        }

        //删除之前的答题记录重新记录
        MemberAnswer::query()->where('uid', $id)->delete();
        Member::query()->where('member_id', $id)->update(['score' => 0]);//分数改0

        $source = 3;//每个题目的分数
        $rightNum = 0;
        $content = $params['content'];
        foreach ($content as $key => $value){
            $memberAnswerData = [];
            $memberAnswerData['uid'] = $id;
            $memberAnswerData['pid'] = $value['pid'];
            $memberAnswerData['answer'] = $value['answer'];
            $memberAnswerData['member_answer'] = $value['correct'];
            $memberAnswerData['score'] = 0;
            $memberAnswerData['type'] = $value['type'];//类型单选还是多选
            $memberAnswerData['num'] = $params['num'];//类型单选还是多选
            if ($value['answer'] !=  $value['correct']){
                //答案错误
                $memberAnswerData['is_correct'] = Problem::PROBLEM_ERROR;
            }else{
                $memberAnswerData['score'] = Problem::PROBLEM_SCORE;
                $rightNum = $rightNum + 1;
                $memberAnswerData['is_correct'] = Problem::PROBLEM_RIGHT;
            }
            //答题明细表
            MemberAnswer::query()->create($memberAnswerData);
        }
        //积分统计

        Member::query()->where('member_id', $id)->update(['score' => $rightNum * Problem::PROBLEM_SCORE]);
        return $this->success(['score' => $rightNum * Problem::PROBLEM_SCORE], '完成答题');

    }

    public function answerFinish($id, Request $request)
    {
        $result = Member::query()->where('member_id', $id)->update(['status' => 1]);

        return $this->success($result, '完成答题');
    }

    /**
     * 题目上传api
     * @param Request $request
     * @return array
     * @throws AppException
     */
    public function import(Request $request)
    {
        $fileCharater = $request->file('file');
        $success_num = $error_num = 0;
        //删除之前得所有题目和答案
        Problem::query()->truncate();
        Answer::query()->truncate();
        Subject::query()->truncate();
        MemberAnswer::query()->truncate();
        OrganizationSubject::query()->update(['subject_id' => '', 'subject_name' => '']);
        OrganizationSubjectNum::query()->truncate();
        try {

            if ($fileCharater->isValid()) { //括号里面的是必须加的哦
                //如果括号里面的不加上的话，下面的方法也无法调用的

                //获取文件的扩展名
                $ext = $fileCharater->getClientOriginalExtension();

                if (!in_array($ext, ['xlsx', 'xls'])){
                    throw new AppException('import_type_is_fail');
                }

                //获取文件的绝对路径
                $path = $fileCharater->getRealPath();

                //定义文件名
                $filename = date('Y-m-d-H-i-s').'.'.$ext;

                //存储文件。disk里面的public。总的来说，就是调用disk模块里的public配置
                Storage::disk('public')->put($filename, file_get_contents($path));

                $directory = storage_path('app') . '/public';

                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
                # 打开文件、载入excel表格
                $spreadsheet = $reader->load($directory . '/' . $filename);
                Config::query()->where('id', 1)->update(['url' => $directory .'/' . $filename]);

                # 获取活动工作薄
                $sheet = $spreadsheet->getActiveSheet();

                # 获取总列数
                $highestColumn = $sheet->getHighestColumn();
                # 获取总行数
                $highestRow = $sheet->getHighestRow();
                # 列数 改为数字显示
                $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);

                for($a = 2;$a <= $highestRow; $a++){
                    $i = 0;
                    $subject = $sheet->getCellByColumnAndRow(1,$a)->getValue();
                    $label = $sheet->getCellByColumnAndRow(2,$a)->getValue();
                    $problemType = $sheet->getCellByColumnAndRow(3,$a)->getValue();
                    $content = $sheet->getCellByColumnAndRow(4,$a)->getValue();
                    $daan = $sheet->getCellByColumnAndRow(5,$a)->getValue();
                    $A = $sheet->getCellByColumnAndRow(6,$a)->getValue();
                    $B = $sheet->getCellByColumnAndRow(7,$a)->getValue();
                    $C = $sheet->getCellByColumnAndRow(8,$a)->getValue();
                    $D = $sheet->getCellByColumnAndRow(9,$a)->getValue();
                    $E = $sheet->getCellByColumnAndRow(10,$a)->getValue();
                    $row_data = [];
                    for ($column = 1; $column <= $highestColumnIndex; $column++) {
                        $row_data[] = $sheet->getCellByColumnAndRow($column, $a)->getValue();
                        $i++;
                    }
                    if(!implode('',$row_data)){
                        //删除空行
                        continue;
                    }

                    $daan = explode(',', $daan);

                    if ($content == '') continue;

                    //插入题库
                    $result = Subject::query()->firstOrCreate([
                        'name' => $subject
                    ]);
                    $data = [
                        'sid' => $result->sid,
                        'type' => $problemType,
                        'label' => $label,
                        'content' => $content,
                        'score' => 2,
                        'correct' => 0,
                        'status' => 0,
                    ];

                    //插入问题
                    $result = Problem::query()->create($data);

                    $correctStr = '';
                    if ($A != ''){
                        $insertData =[];
                        $insertData['content'] = $A;
                        $insertData['pid'] = $result->pid;
                        $insertData['is_correct'] = 1;

                        $resultA = Answer::query()->create($insertData);
                        if (in_array('A',$daan)){
                            $correctStr = $correctStr.',' . $resultA->aid;
                        }

                    }

                    if ($B != ''){
                        $insertData =[];
                        $insertData['content'] = $B;
                        $insertData['pid'] = $result->pid;
                        $insertData['is_correct'] = 1;

                        $resultB = Answer::query()->create($insertData);
                        if (in_array('B',$daan)){
                            $correctStr = $correctStr.',' . $resultB->aid;

                        }

                    }

                    if ($C != ''){
                        $insertData =[];
                        $insertData['content'] = $C;
                        $insertData['pid'] = $result->pid;
                        $insertData['is_correct'] = 1;

                        $resultC = Answer::query()->create($insertData);

                        if (in_array('C',$daan)){
                            $correctStr = $correctStr .',' . $resultC->aid;

                        }

                    }

                    if ($D != ''){
                        $insertData =[];
                        $insertData['content'] = $D;
                        $insertData['pid'] = $result->pid;
                        $insertData['is_correct'] = 1;

                        $resultD = Answer::query()->create($insertData);

                        if (in_array('D',$daan)){
                            $correctStr = $correctStr. ',' . $resultD->aid;

                        }

                    }

                    if ($E != ''){
                        $insertData =[];
                        $insertData['content'] = $E;
                        $insertData['pid'] = $result->pid;
                        $insertData['is_correct'] = 1;

                        $resultD = Answer::query()->create($insertData);

                        if (in_array('E',$daan)){
                            $correctStr = $correctStr. ',' . $resultD->aid;

                        }

                    }

                    $correctStr = trim($correctStr, ',');

                    //进行更改题目答案表

                    Problem::query()->where('pid', $result->pid)->update(['correct' => $correctStr]);

                    if ($result){
                        $success_num = $success_num +1;
                    }else{
                        $error_num = $error_num + 1;
                    }
                }
            }
            $data['success_num'] = $success_num;
            $data['error_num'] = $error_num;
            return $this->success($data);

        } catch (\ Exception $exception) {
            throw new AppException($exception->getMessage());

        }

    }


    public function problemCheck($id, Request $request)
    {
        $member = Member::query()->where('member_id', $id)->first()->toArray();


        $today = MemberAnswer::query()
            ->where('uid', $id)
            ->whereBetween('created_at', [date('Y-m-d'), date('Y-m-d', strtotime('+1 day'))])
            ->get()->toArray();
        $status = 0;
        if ($member['num'] >= 20){
            if ($member['hundred_reward'] == 1){
                //领取了
                if (count($today) >= 25){
                    $status =2;
                }

            }else{
                $status = 1;

            }
        }

        if (count($today) >= 25){

            $status = 2;
        }

        return $this->success(['status' => $status], '获取成功');

    }

    public function getSubjectQuestion($id)
    {
        $data = Problem::query()->where('sid', $id)->get()->toArray();

        foreach ($data as $key => $value){
            $data[$key]['answer'] = Answer::query()->where('pid', $value['pid'])->get()->toArray();
        }

        return $this->success($data);
    }

    public function getOrganizationSubject($id)
    {
//        $data = OrganizationSubject::query()->where('organization_id', $id)->first()->toArray();

        $result = Subject::query()->get()->toArray();

        return $this->success($result);

    }

    public function getConfig()
    {
        $config = Config::query()->first();
        return $this->success($config);
    }

    public function updateProblemInfo($id, Request $request)
    {
        $params = $request->all();//
        $problem = Problem::query()->where('pid', $id)->first();
        if (!$problem){
            return $this->errorCode(200, [], '对不起，题目不存在');
        }

        if (!isset($params['content']) || empty($params['content'])){
            return $this->errorCode(200, [], '对不起，题目信息有误');
        }

        $result = Problem::query()->where('pid', $id)->update(['content' => $params['content']]);
        return $this->success($result);
    }

    public function updateAnswerInfo($id, Request $request)
    {
        $params = $request->all();//
        $answer = Answer::query()->where('aid', $id)->first();
        if (!$answer){
            return $this->errorCode(200, [], '对不起，答案不存在');
        }

        if (!isset($params['content']) || empty($params['content'])){
            return $this->errorCode(200, [], '对不起，答案信息有误');
        }

        $result = Answer::query()->where('aid', $id)->update(['content' => $params['content']]);
        return $this->success($result);
    }


    /**
     * 获取题目
     * Notes:
     * Date: 2022/12/9 11:02
     * @param Request $request
     * @return array
     * @author: 王文文
     */
    public function getProblem(Request $request)
    {
        $params = $request->all();
        $build = Problem::query();

        $pageSize = $request->input('pageSize', 50);

        if (isset($params['content']) || !empty($params['content'])){
            $content = $params['content'];
            $build = $build->where('content', 'like', "%$content%");
        }
        $data = $build->paginate($pageSize)->toArray();
        return $this->success($data);
    }

    /**
     * Notes:
     * Date: 2022/12/9 11:02
     * @param $id
     * @param Request $request
     * @author: 王文文
     */
    public function getAnswerByProblem($id, Request $request)
    {
        $params = $request->all();
        $build = Answer::query();
        if (!isset($params['pid']) || empty($params['pid'])){
            return $this->errorCode(200, [], '对不起，题目不存在');
        }
        $build = $build->where('pid', $params['pid']);
        $data = $build->get()->toArray();
        return $this->success($data);
    }





}